/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2024-05-17
 * Time: 22:42
 */
public class BinarySearchTree {
    static class TreeNode {
        public  int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public TreeNode root;

    public TreeNode search(int key) {
        TreeNode cur = root;
        while(cur != null) {
            if(cur.val > key) {
                cur = cur.left;
            }else if(cur.val < key) {
                cur = cur.right;
            }else {
                return cur;
            }
        }
        return null;
    }

    public void insert(int val) {
        TreeNode newnode = new TreeNode(val);
        if(root == null) {
            root = newnode;
            return;
        }
        TreeNode prev = null;
        TreeNode cur = root;
        while(cur != null) {
            if(cur.val > val) {
                prev = cur;
                cur = cur.left;
            }else if(cur.val < val) {
                prev = cur;
                cur = cur.right;
            }else {
                return;
            }
        }
        if(prev.val > val) {
            prev.left = newnode;
        }else {
            prev.right = newnode;
        }
    }

    public void delet(int val) {
        if(root == null) {
            return;
        }
        TreeNode cur = root;
        TreeNode prev = null;
        while(cur != null) {
            if(cur.val > val) {
                prev = cur;
                cur = cur.left;
            }else if(cur.val < val) {
                prev = cur;
                cur = cur.right;
            }else {
                break;
            }
        }


        if(cur.left == null) {
            if(cur == root) {
                root = root.right;
            }else if(prev.left == cur) {
                prev.left = cur.right;
            }else {
                prev.right = cur.right;
            }
        }else if(cur.right == null) {
            if(cur == root) {
                root = root.left;
            }else if(prev.left == cur) {
                prev.left = cur.left;
            }else {
                prev.right = cur.left;
            }
        }else {
            TreeNode curN = cur.right;
            TreeNode prevN = cur;
            while(curN.left != null) {
                prevN = curN;
                curN = curN.left;
            }
            cur.val = curN.val;
            if(prevN.left == curN) {
                prevN.left = curN.right;
            }else {
                prevN.right = curN.right;
            }
        }

    }

}
